package com.link.base.base.saleactivity.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.model.Coupons;
import com.link.base.base.coupons.service.CollectRecordService;
import com.link.base.base.coupons.service.CouponsService;
import com.link.base.base.saleactivity.model.AccntCampMonitor;
import com.link.base.base.saleactivity.model.Odds;
import com.link.base.base.saleactivity.model.SaleActivity;
import com.link.base.base.saleactivity.service.OddsService;
import com.link.base.base.saleactivity.service.RaffleDetailService;
import com.link.base.base.saleactivity.service.SaleActivityService;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author wangdawei
 * @date 2018/6/10
 * <p>Description 活动的新建,编辑.大转盘活动抽奖</p>
 */
@Controller
@RequestMapping("/link/saleActivity")
public class SaleActivityController extends BasicController<SaleActivity> {
    /**验证码缓存时key值后缀*/
    private static final String VCODECACHE_KEYSUFFIX = "#MarketingCampaignVCode";
    private static final int UNLIMITED_REFFLEWINTIMES = 999999;
    private static final int RESTTIMES_LIMITSHOW = 100000;
    @Resource
    private RaffleDetailService raffleDetailService;

    @Resource
    private SaleActivityService saleActivityService;

    @Resource
    private AccountService accountService;

    @Resource
    private CouponsService couponsService;

    @Resource
    private CollectRecordService collectRecordService;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private OddsService oddsService;

    @Resource
    private UserService userService;

    @Override
    public BasicService<SaleActivity> getBasicService() throws Exception {
        return saleActivityService;
    }

    /**
     * 根据条件查询记录, 门店客户, 渠道商登录查询活动列表接口（品牌商登录不适用，品牌商无acctId）
     * @author: wangdawei
     * @param entity
     * @Date: 2018/5/19
     */
    @RequestMapping(value = "/queryStoreAcntByExamplePage")
    @ResponseBody
    public Map<String, Object> queryStoreAcntByExamplePage(@JsonParam QueryParams qps,@JsonParam  SaleActivity entity, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            CoreUser user = UserUtil.getUser();
            Long accntId = user.getAcctId();
            Account acct = new Account();
            acct.setId(accntId);
            Account accnt = accountService.queryById(acct);
            String acctLevel = accnt.getAcctLevel();
            String acctType = accnt.getAcctType();
            entity.setAccntId(accntId);
            if (accnt != null) {
                if (StringUtils.isNotBlank(acctLevel)) {
                    entity.setStoreLevel(acctLevel);
                }
                if (StringUtils.isNotBlank(accnt.getAcctChileType())) {
                    entity.setStoreType(accnt.getAcctChileType());
                }
            }

            if ( null != accntId) {
                entity.setAccntId(accntId);
            }
            Long orgId = accnt.getOrgId();
            if (null != orgId) {
                entity.setOrgId(orgId);
            }
            qps.preDealSecurity(request);
            SaleActivity t = (SaleActivity) BasicModel.transformClass(entity, qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            List<SaleActivity> list = new ArrayList<SaleActivity>();
            //品牌商登录没有acctId
            if (accnt != null) {
                /*
                 * 门店商登录
                 * */
                String terminal = "Terminal";
                String terminalEmployee = "TerminalEmployee";
                if (terminal.equals(acctType) && terminalEmployee.equals(user.getEmpType())) {
                    list = saleActivityService.queryStoreAcntByExamplePage(t);
                }
                /*
                 * 渠道商登录
                 * */
                String dealer = "Dealer";
                String dealerEmployee = "DealerEmployee";
                if (dealer.equals(acctType) && dealerEmployee.equals(user.getEmpType())) {
                    list = saleActivityService.queryCeStoreAcntByExamplePage(t);
                }
            }
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 活动列表点击按钮改变状态
     * @author: wangdawei
     * @param entity
     * @Date: 2018/5/19
     */
    @RequestMapping(value = "/updActivityStuUpsert")
    @ResponseBody
    public Map<String, Object> updActivityStuUpsert(@JsonParam QueryParams qps,@JsonParam  SaleActivity entity,
                                                    HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            String inatcStr = request.getParameter("inact");
            SaleActivity saleActivityNew = new SaleActivity();
            SaleActivity saleActivity = saleActivityService.queryById(entity.getId());
            if (inatcStr != null && inatcStr != "") {
                if (saleActivity != null) {
                    saleActivity.setActivityState("Inactive");
                    saleActivityService.update(saleActivity);
                    saleActivityNew = saleActivityService.queryById(entity.getId());
                } else {
                    throw new BasicControllerException("活动为空!");
                }
            } else {
                switch (saleActivity.getActivityState()) {
                    case ("New"):
                        /*Boolean flag = true;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
                        String date = sdf.format(new Date());
                        if (saleActivity.getActivityEndDate().compareTo(date) < 0
                                || saleActivity.getActivityStartDate().compareTo(date) > 0 ) {
                            flag = false;
                        }
                        if (flag) {
                            saleActivity.setActivityState("InProgress");
                        }*/
                        saleActivity.setActivityState("InProgress");
                        break;
                    case ("Inactive"):
                        saleActivity.setActivityState("InProgress");
                        break;
                    case ("InProgress"):
                        saleActivity.setActivityState("Completed");
                        break;
                    case ("Completed"):
                        saleActivity.setActivityState("InProgress");
                        break;
                    default:
                        break;
                }
                saleActivityService.update(saleActivity);
                saleActivityNew = saleActivityService.queryById(entity.getId());
            }
            result.put("success", true);
            result.put("rows", saleActivityNew);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 通过活动id查询大转盘h5页面详细信息, 以及抽奖次数的显示
     * @author: wangdawei
     * @param entity
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/querybigWheelInfoByAtyId")
    @ResponseBody
    public Map<String, Object> querybigWheelInfoByAtyId(@JsonParam QueryParams qps,@JsonParam SaleActivity entity, HttpSession session,
                                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            SaleActivity saleActivity = saleActivityService.queryById(entity);
            if (saleActivity != null) {
                saleActivity.setActTime("活动时间：" + saleActivity.getActivityStartDate() + "-" + saleActivity.getActivityEndDate());
                saleActivity.setPhoneNum(entity.getPhoneNum());
            }
            /*
             * arry【0】 返回大转盘剩余抽奖次数，arry【1】 返回组合字符串，用于判断提示客户不能抽奖原因
             * */
            Object[] arry = saleActivityService.querybigWheelInfoByAtyIdAndAcctId(saleActivity, qps, request);
            result.put("success", true);
            result.put("rows", saleActivity);
            result.put("total", arry[0]);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 单击抽奖按钮
     * @author: wangdawei
     * @param entity
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/reffle")
    @ResponseBody
    public Map<String, Object> reffle(@JsonParam QueryParams qps,@JsonParam SaleActivity entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String telNum = entity.getPhoneNum();
        Odds oddsResult = new Odds();
        try {
            User user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
            //活动id拿到活动下的奖品
            Coupons coupons = new Coupons();
            coupons.setActivityId(entity.getId());
            coupons.setPageFlag(false);
            //计算客户的当日抽奖剩余次数
            List<Coupons> list = new ArrayList<Coupons>();
            list = couponsService.queryByExamplePage(coupons);
            SaleActivity act = saleActivityService.queryById(entity);
            act.setCouponsList(list);
            act.setPhoneNum(telNum);
            //剩余抽奖次数
            Object[] arry = saleActivityService.querybigWheelInfoByAtyIdAndAcctId(act, qps, request);
            Odds odds = new Odds();
            odds.setActivityId(entity.getId());
            String accntId = (String) arry[2];
            SaleActivity actSal = saleActivityService.queryById(entity);
            String inactive = "Inactive";
            String completed = "Completed";
            String numberLimited = "NumberLimited";
            //判断活动是否已过期
            if (!inactive.equals(actSal.getActivityState()) && !completed.equals(actSal.getActivityState())) {
                if (numberLimited.equals(act.getPrizetmLimtType()) || numberLimited.equals(act.getDayprizetmLimtType())) {
                    if (actSal.getDayprizetmLimtnum() == null) {
                        actSal.setDayprizetmLimtnum(UNLIMITED_REFFLEWINTIMES);
                    }
                    if (actSal.getPrizetmLimtnum() == null) {
                        actSal.setPrizetmLimtnum(UNLIMITED_REFFLEWINTIMES);
                    }
                    //判断消费者总终奖或者日中奖次数是否已超过次数限制，没超过则可以继续抽奖
                    if ((int)arry[3] >= actSal.getPrizetmLimtnum()
                            || (int)arry[3] >= actSal.getDayprizetmLimtnum()) {
                        oddsResult = saleActivityService.reffle(odds, arry, actSal, Long.parseLong(accntId));
                        String win = "Win";
                        if (win.equals(oddsResult.getPromptClass()) && null != oddsResult.getReffleId()) {
                            Odds odds1 = new Odds();
                            odds1.setId(oddsResult.getReffleId());
                            oddsResult.setCanGet("N");
                            odds1.setAnonymousFlag("Y");
                            odds1.setPostnId(user.getPostnId());
                            oddsService.update(odds1);
                            if ((int)arry[3] <= actSal.getPrizetmLimtnum()
                                    && (int)arry[4] >= actSal.getDayprizetmLimtnum()) {
                                oddsResult.setPrompt("今日中奖次数达到上限，明天再来继续中大奖吧");
                            } else {
                                oddsResult.setPrompt("总中奖次数达到上限,给其他小伙伴一些中奖机会吧");
                            }
                        }
                    } else {
                        oddsResult = saleActivityService.reffle(odds, arry, actSal, Long.parseLong(accntId));
                    }
                } else {
                    oddsResult = saleActivityService.reffle(odds, arry, actSal, Long.parseLong(accntId));
                }
            } else {
                oddsResult.setPromptClass("NoPrize");
                oddsResult.setPrompt("抱歉活动已结束");
            }
            if (arry[0] != null && (int) arry[0] > RESTTIMES_LIMITSHOW) {
                //表示抽奖次数无限制
                arry[0] = "NoLimit";
            }
            oddsResult.setAnonymousFlag("Y");
            result.put("success", true);
            result.put("rows", oddsResult);
            result.put("total", arry[0]);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 短息验证接口，如果用户信息不存在就创建一条用户记录
     * @author: wangdawei
     * @param acct
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/phoneMsgVerify")
    @ResponseBody
    public Map<String, Object> phoneMsgVerify(@JsonParam QueryParams qps,@JsonParam Account acct, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String vCode = request.getParameter("vCode");
        String id = request.getParameter("activityId");
        Boolean flag = true;
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            String ralvCode = jedis.get(acct.getMobilePhone1() + VCODECACHE_KEYSUFFIX);

            if (StringUtils.isNotBlank(ralvCode) && vCode.equals(ralvCode)) {
                //验证成功删除rediesKey
                jedis.del(acct.getMobilePhone() + VCODECACHE_KEYSUFFIX);
            } else {
                flag = false;
            }
            result.put("success", flag);
            result.put("result", acct.getMobilePhone1());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 新建一个活动，包括优惠券、区域、门店，优惠券品牌，系列，大转盘活动抽奖规则，优惠券同步到微信，以及生成二维码图片等
     * @author: wangdawei
     * @param entity
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/newSaleActivity")
    @ResponseBody
    public Map<String, Object> newSaleActivity(@RequestBody SaleActivity entity, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            saleActivityService.insertSaleActivity(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据id获取活动包括优惠券、区域、门店，优惠券品牌，系列，大转盘活动抽奖规则，同步微信状态等
     * @author: wangdawei
     * @param entity
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/getSaleActivtyById")
    @ResponseBody
    public Map<String, Object> getSaleActivtyById(@RequestBody SaleActivity entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            SaleActivity saleActivity = saleActivityService.getSaleActivityById(entity);
            result.put("success", true);
            result.put("result", saleActivity);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 编辑活动信息，包括优惠券、区域、门店，优惠券品牌，系列，大转盘活动抽奖规则，同步微信状态等
     * @author: wangdawei
     * @param entity
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/updateSaleActivity")
    @ResponseBody
    public Map<String, Object> updateSaleActivity(@RequestBody SaleActivity entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            saleActivityService.updateSaleActivity(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据活动id 获取活动内容并获取活动下的优惠券信息
     * @author: wangdawei
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/queryActivityAndCouponsList")
    @ResponseBody
    public Map<String, Object> queryActivityAndCouponsList(@JsonParam QueryParams qps, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String id = request.getParameter("id");
        Coupons entity = new Coupons();
        try {
            SaleActivity saleActivity = new SaleActivity();
            saleActivity = saleActivityService.queryById(Long.parseLong(id));
            entity.setActivityId(Long.parseLong(id));
            entity.setPageFlag(false);
            List<Coupons> couponsList = couponsService.queryByExamplePage(entity);
            saleActivity.setCouponsList(couponsList);
            result.put("success", true);
            result.put("rows", saleActivity);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        }
        return result;
    }

    /**
     * 根据客户电话号码查看该电话号码下的所有优惠券
     * @author: wangdawei
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/queryCouponsByPhoneNum")
    @ResponseBody
    public Map<String, Object> queryCouponsByPhoneNum(@JsonParam QueryParams qps, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String phoneNum = request.getParameter("phoneNum");
        List<Object> list = new ArrayList<>();
        Account entity = new Account();
        try {
            qps.addFilter(new Filter("mobilePhone1", Filter.OP_EQUAL, phoneNum));
            qps.preDealSecurity(request);
            Account t = (Account) BasicModel.transformClass(entity.getClass(), qps);
            t.setPageFlag(false);
            List<Account> accountList = accountService.queryByExamplePage(t);
            for (int i = 0; i < accountList.size(); i++) {
                CollectRecord collectRecord = new CollectRecord();
                collectRecord.setPageFlag(false);
                collectRecord.setCorpid(UserUtil.getUser().getCorpid());
                collectRecord.setAccntId(accountList.get(i).getId());
                List<CollectRecord> collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
                if (collectRecordList.size() != 0) {
                    list.add(collectRecordList);
                }
            }
            result.put("result", list);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        }
        return result;
    }


    /**
     * 获取背景音乐默认路径
     * @author: wangdawei
     * @date: 2018/5/19
     */
    @RequestMapping(value = "/getDefaultMusicPath")
    @ResponseBody
    public Map<String, Object> getDefaultMusicPath() throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(8);
        CoreUser user = UserUtil.getUser();
        try {
            String defaultMusicPath = PropertyUtil.getProperty("defaultBackgroundMusicPath", user.getCorpid());
            result.put("result", defaultMusicPath);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SaleActivity>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        }
        return result;
    }

    /**
     * 查询一条记录,特殊需求
     * @author wangdawei
     * @param entity
     * @date: 2018/5/1
     */
    @RequestMapping(value = "/newQueryById")
    @ResponseBody
    public Map<String, Object> newQueryById(@RequestBody SaleActivity entity, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            // 获取一个默认登录用户
            User user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
            SaleActivity saleActivity = saleActivityService.queryById(entity);
            result.put("result", saleActivity);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 分享领券活动-加载页面
     * @author: wangdawei
     * @param entity
     * @date 2018/11/20
     */
    @RequestMapping(value = "/shareCouponLoading")
    @ResponseBody
    public Map<String, Object> shareCouponLoading(@RequestBody SaleActivity entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> map = new HashMap<>(8);
        try {
            entity = saleActivityService.shareCouponLoading(entity);
            map.put("success", true);
            map.put("newRow", entity);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();

        }
        return map;
    }

    /**
     * 小程序-加载活动详情页面
     * @author: wangdawei
     * @param entity
     * @date 2018/11/20
     */
    @RequestMapping(value = "/showCompainDetail")
    @ResponseBody
    public Map<String, Object> showCompainDetail(@RequestBody SaleActivity entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> map = new HashMap<>(8);
        try {
            entity = saleActivityService.showCompainDetail(entity);
            map.put("success", true);
            map.put("newRow", entity);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }

    /**
     * 分享优惠券-入口
     * @author: wangdawei
     * @param entity
     */
    @RequestMapping(value = "/shareCoupons")
    @ResponseBody
    public Map<String, Object> shareCoupon(@RequestBody SaleActivity entity, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> map = new HashMap<>(8);
        try {
            map = saleActivityService.shareCoupons(entity);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }


    /**
     * 判断是否是会员
     * @return
     */
    @RequestMapping(value = "/isMpmeber")
    @ResponseBody
    public Map<String, Object> isMpmeber(@RequestBody  SaleActivity saleActivity) {
        Map<String,Object> map = new HashMap<>(4);
        try {
            map = saleActivityService.isMpmeber(saleActivity);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }

    /**
     * 查询已分享好友列表
     * @param accntCampMonitor
     * @return
     */
    @RequestMapping(value = "/accountList")
    @ResponseBody
    public Map<String, Object> accountList(@RequestBody  AccntCampMonitor accntCampMonitor) {
        Map<String,Object> map = new HashMap<>(8);
        try {
            map = saleActivityService.accountList(accntCampMonitor);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }

    /**
     * 导购助手app-生成二维码图片
     * @param entity
     * @return
     */
    @RequestMapping(value = "/createQrCode")
    @ResponseBody
    public Map<String, Object> createQrode(@RequestBody  SaleActivity entity) {
        Map<String,Object> map = new HashMap<>(8);
        try {
            SaleActivity saleActivity = new SaleActivity();
            saleActivity = saleActivityService.createQrCode(entity);
            map.put("success", true);
            map.put("newRow", saleActivity);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }

    /**
     * 生成大转盘H5页面，H5图片
     * @param entity
     * @return
     */
    @RequestMapping(value = "/createH5UrlCode")
    @ResponseBody
    public Map<String, Object> createH5UrlCode(@RequestBody SaleActivity entity) {
        Map<String,Object> map = new HashMap<>(4);
        try {

            SaleActivity saleActivity = new SaleActivity();
            saleActivity = saleActivityService.createH5UrlCode(entity);
            map.put("success", true);
            map.put("newRow", saleActivity);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }

    /**
     * 大屏小程序筛选掉不需要的活动
     * @author KuangRuifeng
     * @date 2018年12月12日
     */
    @RequestMapping(value = "/queryByMpScreenPage")
    @ResponseBody
    public Map<String, Object> queryByMpScreenPage(@JsonParam QueryParams qps, @JsonParam SaleActivity saleActivity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            Long loginCorpId = UserUtil.getUser().getLoginCorpId();
            SaleActivity sa = new SaleActivity();
            sa.setLoginCorpId(loginCorpId);
            // 先查询出在其他设备上展示过的活动id
            List<String> idList = saleActivityService.queryFilterIdList(sa);
            String[] idArr = new String[idList.size()];
            idArr = idList.toArray(idArr);
            // 构造一个filters对象
            Map<String, Object> filterMap = new HashMap<>(4);
            filterMap.put("id", "ID_FILTER");
            filterMap.put("property", "id");
            filterMap.put("operator", "not in");
            filterMap.put("value", Arrays.toString(idArr));
            // 合并到查询参数中
            String filtersRaw = qps.getFiltersRaw();
            if (StringUtils.isNotBlank(filtersRaw)) {
                String filterStr = ", " + JsonUtil.toString(filterMap) + "]";
                filtersRaw = filtersRaw.substring(0, filtersRaw.length() - 1) + filterStr;
            } else {
                filtersRaw = "[" + JsonUtil.toString(filterMap) + "]";
            }
            qps.setFiltersRaw(filtersRaw);
            result = super.queryByExamplePage(qps, saleActivity, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 查询红包活动并校验
     * @author 路江
     * @param entity
     * @return
     */
    @RequestMapping(value = "/queryRedPackActivity")
    @ResponseBody
    public Map<String, Object> queryRedPackActivity(@RequestBody SaleActivity entity) {
        Map<String,Object> map = new HashMap<>(4);
        SaleActivity saleActivity = new SaleActivity();
        try {
            saleActivity = saleActivityService.queryById(entity);
            map = saleActivityService.queryRedPackActivity(entity);
            map.put("success", true);
        } catch (Exception e) {
            map.put("rule",saleActivity.getIntroduction());
            map.put("success", false);
            map.put("msg", e.getMessage());
            e.getMessage();
        }
        return map;
    }
}






